import {_decorator, Component, JsonAsset, Layout, Prefab, resources, error, SpriteAtlas, Node} from 'cc';
import {Pools} from "../framework/entity/ao/Pools";
import {logUtil} from "../framework/util/logUtil";
import {ResourceUtil} from '../framework/util/ResourceUtil';

const {ccclass, property} = _decorator;

//挂载在Layout组件下
@ccclass('UILayoutBtn')
export class UILayoutBtn extends Component {
    //按钮预制体
    @property(Prefab)
    btnPrefab: Prefab | null = null;

    //按钮组
    btnPool: Pools<string, Node> ;//内存池,为了缓解resetString方法
    //按钮资源路径
    btnPath: string
    //图集
    plist:any
    //按钮数据路径
    btnJsonPath: string
    //按钮数据
    btnJson: any

    //技能组布局
    layout: Layout;
    //是否异步:true
    isAsync:boolean=true;

    //日志控制器
    log = logUtil.instance
    logLevel = "UILayoutBtn"

    onLoad() {

        this.btnPool= new Pools()
        this.layout = this.node.getComponent(Layout);
        if(this.isAsync){
            this.init()
        }
        /*setTimeout(() => {

        }, 8000);*/
    }

    /**
     * 加载敌人模型
     */
    async init(): Promise<void> {
        //加载数据资源
        if(this.isAsync){
            let json: any = await ResourceUtil.loadResType(this.btnJsonPath, JsonAsset)
            this.btnJson = json.json.RECORDS;

            return new Promise((resolve) => {
                this.log.log(this.logLevel, `init`);
                this.preThing()

                resources.load(this.btnPath, SpriteAtlas, (err: any, plist: any) => {
                    this.log.log(this.logLevel, `加载资源`);
                    if (err) {
                        error(err.message || err);
                        return;
                    }
                    //处理图集
                    this.btnJson.forEach((btnData: any) => {
                        this.createBtnPool(this.btnPrefab, plist, btnData);
                    });

                    this.show()
                })

                this.log.log(this.logLevel, `加载结束`);
            });
        }else {
            return new Promise((resolve) => {
                this.preThing()
                //处理图集
                this.btnJson.forEach((btnData: any) => {
                    this.createBtnPool(this.btnPrefab, this.plist, btnData);
                });

                this.show()
            });
        }

    }

    /**
     * 预制体处理
     * @param prefab {Prefab} 状态数据
     * @param plist {any} 图集
     * @param btnData {any)} 每个独立的json数据
     * @author zgn
     */
    createBtnPool(prefab: Prefab, plist: any, btnData: any) {
        this.log.log(this.logLevel, `super-createBtnPool`);
    }
    //加载前动作
    preThing(){

    }
    //加载后展示
    show() {
        this.layout.updateLayout();
    }

    onDestroy() {
        this.btnPool.destroyAll();
    }

    constructor(btnPath: string, btnJsonPath: string) {
        super();
        this.btnPath = btnPath;
        this.btnJsonPath = btnJsonPath;
    }
}


